//index.js
//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
     showone: true,
     showtwo: true,
     hiddenmodalput: true,
     placeholder: '',
     content: '',
     openId: null,
     animation_one: null,
     plan_item_status: true,
     list: [
      {
        id: 'todo',     //id
        name: '未开始',  //name
        open: false,    //是否展开
        color: '#f4ea2a',  //背景色
        isOpe: true,      //是否展示操作按钮
        operation: '开始',  //操作名
        none_plan: '当前没有Plan去做哦赶快新建Plan吧~',
         plans: []  //计划列表
      },
      {
        id: 'doing',
        name: '进行中',
        open: false,
        color: '#1296db',
        isOpe: true,
        operation: '完成',
        none_plan: '当前没有Plan正在进行哦~',
        plans: []
      },
      {
        id: 'done',
        name: '已完成',
        open: false,
        color: '#1afa29',
        isOpe: false,
        none_plan: '当前没有已经完成的Plan哦~',
        plans: []
      }
    ]
  },

  one: function () {
    this.setData({
      showone: true,
      list: [
        {
          id: 'todo',     //id
          name: '未开始',  //name
          open: true,    //是否展开
          color: '#f4ea2a',  //背景色
          isOpe: true,      //是否展示操作按钮
          operation: '开始',  //操作名
          none_plan: '当前没有Plan去做哦赶快新建Plan吧~',
          plans: [{
            content: "样例可右滑删除",
            _id: '123456',
            plan_item_status: true,
            status: 0,
            tag: [{ _id: "0123456", name: "运动" }],
          }]  //计划列表
        },
        {
          id: 'doing',
          name: '进行中',
          open: false,
          color: '#1296db',
          isOpe: true,
          operation: '完成',
          none_plan: '当前没有Plan正在进行哦~',
          plans: []
        },
        {
          id: 'done',
          name: '已完成',
          open: false,
          color: '#1afa29',
          isOpe: false,
          none_plan: '当前没有已经完成的Plan哦~',
          plans: []
        }
      ],
      open: true,
      showtwo: false,
    })
  },

  two: function () {
    this.setData({
      showtwo: true,
    })
  },

  onPullDownRefresh() {
    // 显示标题栏进度条效果
    wx.showNavigationBarLoading();
    this.getPlans(0);
    this.getPlans(1);
    this.getPlans(2);
    // 取消标题栏进度条效果
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh()
  },

  onLoad: function(){
    var self = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          wx.cloud.callFunction({
            // 云函数名称
            name: 'login',
            // 传给云函数的参数
            data: {
              code: res.code
            },
            success: function (res) {
              app.globalData.openId = JSON.parse(res.result).openid
              self.setData({
                openId: app.globalData.openId
              })
              wx.cloud.callFunction({
                // 云函数名称
                name: 'isExist',
                // 传给云函数的参数
                data: {
                  _openid: app.globalData.openId
                },
                success: function (res) {
                  if(!res.result.data.length){
                    self.setData({
                      showone: false
                    })
                    wx.cloud.callFunction({
                      name: 'register',
                      data: {
                        _openid: app.globalData.openId
                      },
                      success: function (res) {
                          
                      },
                      fail: console.error
                    })
                  }else{
                    self.getPlans(0)
                    self.getPlans(1)
                    self.getPlans(2)
                  }
                },
                fail: console.error
              })
            },
            fail: console.error
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
    var animation = wx.createAnimation({
      duration: 1000,//旋转速度毫秒，数值越小速度越快
      timingFunction: 'linear',
    });

    animation.rotate(20). top(100000).step()//旋转动画180为角度.360是一周

    var param = "animation_one";//动画的名字，与wxml的animation一样
    var json = '{"' + param + '":""}'
    json = JSON.parse(json);
    json[param] = animation.export()
    self.setData(json)
    },

  //获取plan内容
  bindKeyInput: function (e) {
    this.setData({
      content: e.detail.value
    })
  },

  //取消发布任务
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });
  },

  //确认发布任务
  confirm: function () {
    var self = this;
    if(this.data.content === ''){
      wx.showToast({
        title: '计划内容不能为空',
        icon: 'none',
        duration: 1000,
        mask: true,
      })
    }else{
      wx.showToast({
        title: '请选择计划所属标签',
        icon: 'none',
        duration: 1000
      }),
      this.setData({
        hiddenmodalput: true
      }),
        wx.showActionSheet({
          itemColor: '#d4237a',
          itemList: ['运动', '学习', '娱乐'],
          success: function (res) {
              switch(res.tapIndex){
                case 0:
                  self.getTagId('运动');
                  break;
                case 1:
                  self.getTagId('学习');
                  break;
                case 2:
                  self.getTagId('娱乐');
                  break;
              }
          },
          fail: function (res) {
            console.log(res.errMsg)
          }
        })
    }
  },

  //获取用户发布任务的标签
  getTagId: function(e){
    var self = this;
    const db = wx.cloud.database()
    db.collection('tag').where({
      name: e
    }).get({
      success: function(res){
        self.setData({
          tagId: res.data[0]._id
        })
        self.releasePlan()
      }
    })
  },

  //获取用户输入的任务内容
  modalinput: function (e) {
    var id = e.currentTarget.id;
    if (id === 'todo') {
      this.setData({
        placeholder: '',
        hiddenmodalput: !this.data.hiddenmodalput
        })
    }
  },

  //展示plans
  kindToggle: function (e) {
    var id = e.currentTarget.id, list = this.data.list;
    for (var i = 0, len = list.length; i < len; ++i) {
      if (list[i].id == id) {
        if(list[i].plans.length == 0){
          wx.showToast({
            title: list[i].none_plan,
            icon: 'none',
            duration: 1000
          })
        }else{
          list[i].open = !list[i].open
        }
      } else {
        list[i].open = false
      }
    }
    this.setData({
      list: list
    });
  },

  //get plans
  getPlans: function (e) {
    var self = this;
    wx.cloud.callFunction({
      // 云函数名称
      name: 'getPlans',
      // 传给云函数的参数
      data: {
        status: e,
        _openid: self.data.openId
      },
      success: function (res) {
        var listn = self.data.list;
        listn[e].plans = res.result.list;
        self.setData({
          list: listn
        })
      },
      fail: console.error
    })
  },
  
  //发布任务
  releasePlan : function(){
    var self = this;
    const db = wx.cloud.database();
    db.collection('plan').add({
      data: {
        release_time: new Date(),
        start_time: null,
        end_time: null,
        status: 0,
        plan_item_status: true,
        content: self.data.content,
        tag_id: self.data.tagId,
        duration: null
      },
      success: function(res){
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 1000,
          mask: true,
        })
        self.getPlans(0)
      }
    })
  },

  //开始一项任务
  operat_plan: function(e){
    var self = this;
    wx.showLoading({
      title: '处理中',
    })
    var json = self.data.list
    var id = e.currentTarget.id
    var status;
    for (var group in json) {
      for (var plan in json[group].plans) {
        if (json[group].plans[plan]._id == id) {
          status = json[group].plans[plan].status;
          console.log(json[group].plans[plan])
          break;
        }
      }
    }
    wx.cloud.callFunction({
      name: "operatePlan",
      data: {
        id: e.target.id,
        status: status
      },
      success: function(res){
        self.getPlans(0)
        self.getPlans(1)
        self.getPlans(2)
        wx.hideLoading()
      }
    })
  },

  //删除一项任务
  delete_plan: function(e){
    var self = this;
    wx.showLoading({
      title: '处理中',
    })
    wx.cloud.callFunction({
      name: "deletePlan",
      data: {
        id: e.target.id
      },
      success: function (res) {
        self.getPlans(0)
        self.getPlans(1)
        self.getPlans(2)
        wx.hideLoading()
      }
    })
  },

  touchS(e) {
    // 获得起始坐标
    this.startX = e.touches[0].clientX;
    this.startY = e.touches[0].clientY;
  },

  touchM(e) {
    var self = this;
    // 获得当前坐标
    this.currentX = e.touches[0].clientX;
    this.currentY = e.touches[0].clientY;
    const x = this.startX - this.currentX; //横向移动距离
    const y = Math.abs(this.startY - this.currentY); //纵向移动距离，若向左移动有点倾斜也可以接受
    var _true, _false
    var json = self.data.list
    var id = e.currentTarget.id
    if (x > 35 && y < 110) {
      for (var group in json) {
        for (var plan in json[group].plans) {
          if (json[group].plans[plan]._id == id) {
            json[group].plans[plan].plan_item_status = false
            _false = json
          } else {
            json[group].plans[plan].plan_item_status = true
          }
        }
      }
      //向左滑是显示删除
      this.setData({
        list: _false
      })
    } else if (x < -35 && y < 110) {
      for (var group in json) {
        for (var plan in json[group].plans) {
          if (json[group].plans[plan]._id == id) {
            json[group].plans[plan].plan_item_status = true
            _true = json
          } else {
            json[group].plans[plan].plan_item_status = true
          }
        }
      }
      //向右滑
      this.setData({
        list: _true
      })
    }
  },

})